<?php
declare (strict_types = 1);

namespace app;

use thans\jwt\facade\JWTAuth;
use think\facade\Config;
use think\Facade\Db;

class After
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        $module = App('http')->getName();
        $controller = $request->controller(true);
        $action = $request->action(true);
        $method = $request->method(true);
        $type = $request->type();
        $url = $request->url(true);
        $ip = $request->ip();
        $param = $request->param(false);
        $agent = $request->header('user-agent');
        $referer = $request->header('referer');

        $config = config('record');

        if ($action == 'login') {
            if (!$config['login']) {
                return $response;
            }
        } else if (!$config['enable']) {
            return $response;
        }

        $rule = Db::name('rule')->where(['module' => $module, 'controller' => $controller, 'action' => $action])->find();

        if ($action != 'login' && !in_array($rule['id'], $config['action'])) {
            return $response;
        }

        $log = [
            'module' => $module,
            'controller' => $controller,
            'action' => $action,
            'method' => $method,
            'type' => $type,
            'param' => json_encode($param),
            'url' => $url,
            'referer' => $referer,
            'ip' => $ip,
            'agent' => $agent,
            //'result' => json_encode($response->getData()), //getCode()
        ];

        if ($action != 'login' && $config['result']) {
            $log['result'] = json_encode($response->getData());
        }

        if ($action != 'login') {
            $payload = JWTAuth::auth();
            $log['uid'] = $payload['id'];
        }

        Db::name('log')->insert($log);

        return $response;
    }
}
